package com.svs.framework.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Calendar;
 
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
 

public class MobileSMSUtils {
	 static Logger logger = LoggerFactory.getLogger(MobileSMSUtils.class) ;
	 private static String apId="xch2";
	 private static String secretKey="xch2019";
	 private static String ecName = "襄阳市农业信息中心";	//集团名称
	 private static String sign = "b83A0BOlL";	//网关签名编码
	 private static String addSerial = "";	//拓展码 填空
	 public static String url = "http://112.35.1.155:1992/sms/norsubmit";//请求url
	 
	 private static String smsContent_register = "您正在申请加入襄阳市农业产业政府推介公共平台，您申请的短信验证码是{1}";
	 private static String smsContent_password = "您正在修改襄阳市农业产业政府推介公共平台的登录密码，身份确认短信验证码是{1}";
	 private static String smsContent_audit = "恭喜您，您的企业信息通过襄阳市农业产业政府推介公共平台审核，接下来请认真填写企业其它信息";
	 private static String param_str = "{1}";
	 
	 public static boolean sendDSMS4Reg(String mobile,String verifyCode ){
		 String content = smsContent_register.replace(param_str, verifyCode);//发送内容
		 return sendMsg(mobile,content)==1;
	 }
	 
	 public static boolean sendDSMS4Passwd(String mobile,String verifyCode ){
		 String content = smsContent_password.replace(param_str, verifyCode);//发送内容
		 return sendMsg(mobile,content)==1;
	 }
	 
	 public static boolean sendDSMS4Audit(String mobile){
		 return sendMsg(mobile,smsContent_audit)==1;
	 }
	 
	 /**
	  * 多用户发送短信信息
	  * @param mobiles 手机号码逗号分隔
	  * @param content 短信内容
	  * @return 返回1表示成功，0表示失败
	  * @throws IOException
	  */
	 public static int sendMsg(String mobiles,String content){
		 Calendar calendar = Calendar.getInstance();		
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 String nowDatestr = sdf.format(calendar.getTimeInMillis()); 
		 content += nowDatestr; //短信内容后跟个日期时间（可有可无），需求要求
		 
		 SendReq sendReq = new SendReq();
		 sendReq.setApId(apId);
		 sendReq.setEcName(ecName);
		 sendReq.setSecretKey(secretKey);
		 sendReq.setContent(content);
		 sendReq.setMobiles(mobiles);
		 sendReq.setAddSerial(addSerial);
		 sendReq.setSign(sign);
		 
		 StringBuffer stringBuffer = new StringBuffer();
		 stringBuffer.append(sendReq.getEcName());
		 stringBuffer.append(sendReq.getApId());
		 stringBuffer.append(sendReq.getSecretKey());
		 stringBuffer.append(sendReq.getMobiles());
		 stringBuffer.append(sendReq.getContent());
		 stringBuffer.append(sendReq.getSign());
		 stringBuffer.append(sendReq.getAddSerial());
		 
		 //System.out.println(stringBuffer.toString());
		 sendReq.setMac(Md5Util.MD5(stringBuffer.toString()).toLowerCase());
		 //System.out.println(sendReq.getMac());
		 
		 String reqText = JSON.toJSONString(sendReq);
		 
		 String encode;
		 int result = 0;
		 try {
			 encode = Base64.encodeBase64String(reqText.getBytes("UTF-8"));
			 String resStr = sendPost(url,encode);
			 SendRes sendRes = JSON.parseObject(resStr,SendRes.class);
			 if(sendRes.isSuccess() && !"".equals(sendRes.getMsgGroup()) && "success".equals(sendRes.getRspcod())){
				 return 1;
			 }
		 } catch (UnsupportedEncodingException e) {
			 logger.error("中国移动云MAS平台发送短信注册验证码异常",e );
		 }
		 return result;
		 
	 }
	 
	 
	 //main方法测试发送短信，返回1表示成功，0表示失败  
	 public static void main(String[] args) throws IOException{
		 String msg = "这是发送短信的内容！";
//		 int result = sendMsg("18558898151",msg);
		 boolean result = sendDSMS4Reg("15267094681","159753");
		 System.out.println("==="+result);
	 }
	 
	    /**
	     * 向指定 URL 发送POST方法的请求
	     *
	     * @param url
	     *            发送请求的 URL
	     * @param param
	     *            请求参数
	     * @return 所代表远程资源的响应结果
	     */
	    private static String sendPost(String url, String param) {
	        OutputStreamWriter out = null;
	 
	        BufferedReader in = null;
	        String result = "";
	        try {
	            URL realUrl = new URL(url);
	            URLConnection conn = realUrl.openConnection();
	            conn.setRequestProperty("accept", "*/*");
	            conn.setRequestProperty("contentType","utf-8");
	            conn.setRequestProperty("connection", "Keep-Alive");
	            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
	            conn.setDoOutput(true);
	            conn.setDoInput(true);
	 
	            out = new OutputStreamWriter(conn.getOutputStream());
	            out.write(param);
	            out.flush();
	 
	 
	            in = new BufferedReader(
	                    new InputStreamReader(conn.getInputStream()));
	            String line;
	            while ((line = in.readLine()) != null) {
	                result += "\n" + line;
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            try {
	                if (out != null) {
	                    out.close();
	                }
	                if (in != null) {
	                    in.close();
	                }
	            } catch (IOException ex) {
	                ex.printStackTrace();
	            }
	        }
	        return result;
	    }
}
